/*
*  功能：缓存视图
*
*/


const ADD_VISITED_ROUTE = "ADD_VISITED_ROUTE"
const REMOVE_VISITED_ROUTE = "REMOVE_VISITED_ROUTE"
const REMOVE_OTHER_ROUTES = "REMOVE_OTHER_ROUTES"
const REMOVE_ALL_ROUTES = "REMOVE_ALL_ROUTES"

//定义state
const state = {
  visitedRoutes: [],
  cachedViewNames: []
}

//定义getters -- 相当于Store的计算属性
const getters = {
  visitedRoutes: function (state, getters) {
    return state.visitedRoutes
  },
  cachedViewNames: function (state, getters) {
    // console.log(state.cachedViewNames)
    return state.cachedViewNames
  }
}

//Mutations
//作用：同步调用 store.commit 方法，更改 Vuex 的 store 中的状态的唯一方法
const mutations = {
  [ADD_VISITED_ROUTE]: function (state, route) {
    if(!state.visitedRoutes.some(item=>item.path === route.path)){
      let item = {
        name: route.name || 'unknown',
        path: route.path,
        title: route.meta.title
      }
      state.visitedRoutes.push(item)

      if(!route.meta.noCache){
        state.cachedViewNames.push(item.name)
      }
    }
  },
  [REMOVE_VISITED_ROUTE]: function (state, route) {
    state.visitedRoutes = state.visitedRoutes.filter(item=>item.path !== route.path)
    state.cachedViewNames = state.cachedViewNames.filter(item=>item !== route.component.name)
  },
  [REMOVE_OTHER_ROUTES]: function (state, route) {
    state.visitedRoutes = state.visitedRoutes.filter(item=>item.path === route.path)
    state.cachedViewNames = state.cachedViewNames.filter(item=>item === route.component.name)
  },
  [REMOVE_ALL_ROUTES]: function (state) {
    state.visitedRoutes = []
    state.cachedViewNames = []
  }
}

//Actions
//作用：1.提交的是 mutation，而不是直接变更状态
//     2.可以包含任意异步操作
const actions = {
  addVisitedRoute: function ({commit}, route) {
    commit(ADD_VISITED_ROUTE, route)
  },
  removeVisitedRoute: function ({commit}, route) {
    commit(REMOVE_VISITED_ROUTE, route)
  },
  removeOtherRoutes: function ({commit}, route) {
    commit(REMOVE_OTHER_ROUTES, route)
  },
  removeAllRoutes: function ({commit}) {
    commit(REMOVE_ALL_ROUTES)
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
